package userslogic

import (
	"common/comHttp"
	"common/dao/model"
	"common/modelrsa"
	"context"
	"errors"
	"gorm.io/gorm"

	"service/internal/svc"
	"service/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type PassReq struct {
	PassWord string `json:"passWord"`
}

type PassResp struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		Message string `json:"message"`
	} `json:"data,omitempty"`
}
type UpdatePassWordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePassWordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePassWordLogic {
	return &UpdatePassWordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePassWordLogic) UpdatePassWord(in *pb.ChangePassReq) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	var (
		req  = PassReq{}
		user = model.SysUser{}
	)
	if in.Uuid == "" {
		return nil, errors.New("uuid is empty")
	}
	if in.PassWord == "" {
		return nil, errors.New("passWord is empty1")
	}
	req.PassWord = in.PassWord
	url := l.svcCtx.Config.Gateway.Server + "/v1/user/Decrypt"

	request, err := comHttp.Request[PassResp](url, comHttp.Post, req)
	if err != nil {
		return nil, err
	}
	if request.Code != 0 {
		return nil, errors.New(request.Message)
	}

	pwd := request.Data.Message

	db := l.svcCtx.DB.Table(model.TableNameSysUser)
	err = db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("uuid = ?", in.Uuid).Find(&user).Error; err != nil {
			return err
		}
		if user.UUID == "" {
			return errors.New("账户不存在")
		}
		password, err := modelrsa.HashPassword(pwd)
		if err != nil {
			return err
		}
		user.Password = password
		if err := tx.Updates(&user).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}
